package gohttp

import (
	"GoWeb/src/config"
	"GoWeb/src/gohttp/dbutils"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

var db *sql.DB

func GoHttp(port string) {
	var err error = nil
	_, err = config.GetIP()
	CheckErr(err)
	db, err = dbutils.Init(dbutils.DbConfig{SqlName: "dab", SqlPwd: "123456", SqlAddress: "118.24.71.63", SqlPort: "3306", SqlDatabaseName: "goWeb"})
	CheckErr(err)
	http.HandleFunc("/", appHandleFunc(MainRoute))
	http.HandleFunc("/login", appHandleFunc(Login))
	http.HandleFunc("/register", appHandleFunc(Register))
	http.HandleFunc("/uploadFile", appHandleFunc(uploadFile))
	err = http.ListenAndServe(":"+port, nil)
	CheckErr(err)
	defer db.Close()
}

type ResultData struct {
	Code     int32       `json:"code"`
	Meg      string      `json:"mag"`
	DebugMeg string      `json:"debugMeg"`
	Data     interface{} `json:"data"`
}

func (r *ResultData) Error() string {
	return r.Meg
}
func NewResultData(data interface{}) *ResultData {
	return &ResultData{Code: 0, Data: data}
}
func NewResultError(code int32, meg string) *ResultData {
	return &ResultData{Code: code, Meg: meg, Data: nil}
}
func (r *ResultData) SetDebugMeg(msg string) *ResultData {
	r.DebugMeg = msg
	return r
}

type appHandleFuncErr func(http.ResponseWriter, *http.Request) (error)

func appHandleFunc(appHandleFuncErr appHandleFuncErr) (func(http.ResponseWriter, *http.Request)) {
	return func(writer http.ResponseWriter, request *http.Request) {
		defer func() {
			i := recover()
			if err, ok := i.(error); ok {
				data := ResultData{Code: -1, Meg: "服务器内部错误", DebugMeg: err.Error()}
				bytes, _ := json.Marshal(data)
				fmt.Fprint(writer, string(bytes))
			}
		}()

		err := appHandleFuncErr(writer, request)
		if v, ok := err.(*ResultData); ok {
			bytes, _ := json.Marshal(v)
			fmt.Fprint(writer, string(bytes))
			return
		}
		if err != nil {
			bytes, _ := json.Marshal(&ResultData{Code: -1, Meg: "服务器内部错误", DebugMeg: err.Error()})
			fmt.Fprint(writer, string(bytes))
		}

	}
}

func CheckErr(err error) {
	if err != nil {
		//fmt.Printf("%T err:%s\n", err, err)
		log.Fatalf("%T err:%s", err, err)
	}
}
